python stdin

python에서 본래 input으로 입력을 받았는데 한번 시간초과가 발생한 문제를 잡고 끼잉끼잉 대다가 stind으로 푸니까 바로 풀려서 정리해보고 앞으로는 stdin을 활용하려고 한다.

input vs sys.stdin

그래서 이 둘은 어떻게 다르길레 시간이 차이나는 걸까

input

input() 은 파이썬 내장함수 이다.
input()에 대한 파이썬 공식 문서

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.

input -> 개행문자 지우기 -> 문자열로 반환 -> Retur

input은 다음과 같은 절차를 거친다.

sys.stdin

sys.stdin doc

File objects used by the interpreter for standard input, output and errors:

내장 함수인 input 과 달리 sys.stdin은 file obeject이다.
사용자의 입력을 받는 Buffer를 만들어 그 buffer에서 읽어들인다.

inputraw_input()을 evaluate 한 결과를 반환하고 sys.stdin.readline()은 한 줄의 문자열을 반환

stdin 사용하기

import sys

sys.stdin

^Z 을 입력받기까지 여러줄을 입력받는다.
개행문자까지 입력된다.
-> strip rstrip 등을 이용해서 제거해줘야한다.

nums = []
for line in sys.stdin:
    nums.append(line)
 
print(nums)
"""
1
2
3
4
5{ #Z}

['1\n', '2\n', '3\n', '4\n', '5\n']
"""

sys.stdin.readline()

x, y = sys.stdin.readline().split()
 
print("x = ", x)
print("y = ", y)
"""
x =  1
y =  2
"""

readline으로 여러줄 입력받기

N = input()
a = [sys.stdin.readline() for _ in range(N)]

references